package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CarListAdapter;
import com.example.administrator.yanfoxconn.adapter.KHHeadListAdapter;
import com.example.administrator.yanfoxconn.bean.JVSchoolInfo;
import com.example.administrator.yanfoxconn.bean.KHInfo;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.SwipeListViewFour;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.Serializable;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用途：人資-訪談記錄 主列表界面
 * Created by Song on 2021/9/14.
 */
public class KHMainListActivity extends BaseActivity implements View.OnClickListener,  DatePicker.OnDateChangedListener  {

    private final int MESSAGE_SET_TYPE = 7;//網絡錯誤
    private final int MESSAGE_SET_STATUS = 8;//網絡錯誤

    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnAdd;//新增
    @BindView(R.id.btn_check)
    Button btnCheck;//查詢
    @BindView(R.id.tv_date_start)
    TextView tvDateStart;//開始時間
    @BindView(R.id.tv_date_end)
    TextView tvDateEnd;//結束時間
    @BindView(R.id.sp_type)
    Spinner spType;//類型
    @BindView(R.id.sp_status)
    Spinner spStatus;//狀態
    @BindView(R.id.lv_kh_head)
    SwipeListViewFour lvKHHead;

    private KHHeadListAdapter khHeadListAdapter;
    private List<KHInfo> KHInfoList;

    private List<KHInfo> typeInfo,statueInfo;//访谈类型，状态
    private String type,statue,iId;

    private String initStartDateTime; // 初始化开始时间
    private Date selectEndTime = null;//所選時間
    private Date curDate = null;//當前時間
    private String curDates;//當前時間
    private SimpleDateFormat formatter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kh_main_list);
        ButterKnife.bind(this);
        btnBack.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        tvDateStart.setOnClickListener(this);
        tvDateEnd.setOnClickListener(this);
        tvTitle.setText("訪談信息");
        btnAdd.setText("新增");
        btnAdd.setVisibility(View.VISIBLE);

        formatter = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        initStartDateTime = formatterUse.format(curDate);
        tvDateStart.setText(formatter.format(curDate));
        tvDateEnd.setText(formatter.format(curDate));
        curDates = formatter.format(curDate);

        date = new StringBuffer();
        getType("i_type");
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_title_right://提交
                Intent intent = new Intent(KHMainListActivity.this,KHAddMainActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_date_start:
                initDateTime();
                show("start");
                break;
            case R.id.tv_date_end:
                initDateTime();
                show("end");
                break;
            case R.id.btn_check:
                check();

                break;
        }
    }
    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     *
     * @param listView
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        KHHeadListAdapter listAdapter = (KHHeadListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    private void clickSeeOrAdd() {
        khHeadListAdapter.setOnClickListenerFour(new KHHeadListAdapter.OnClickListenerFour() {

            @Override
            public void OnClickListenerSee(int position) {//查看
                Intent intent = new Intent(KHMainListActivity.this, KHPeopleListActivity.class);
                intent.putExtra("type", statueInfo.get(position).getI_TYPE());
                intent.putExtra("date", statueInfo.get(position).getI_DATE());
                intent.putExtra("position", statueInfo.get(position).getI_AREA()+statueInfo.get(position).getI_BUILDING()+statueInfo.get(position).getI_POSITION());
                intent.putExtra("id", statueInfo.get(position).getI_ID());
                startActivity(intent);
            }

            @Override
            public void OnClickListenerDel(int position) {//刪除
                if (statueInfo.get(position).getISDELETE().equals("N")){
                    ToastUtils.showShort(KHMainListActivity.this,"存在人員信息，不予刪除！");
                }else{
                aboutAlert("確認刪除？無法修復！",Constants.MESSAGE_TOAST);
                iId=statueInfo.get(position).getI_ID();
                }
            }

            @Override
            public void OnClickListenerAdd(int position) {//增加
                Intent intent = new Intent(KHMainListActivity.this, KHPeopleAddAndDetailActivity.class);
                intent.putExtra("id", statueInfo.get(position).getI_ID());
                intent.putExtra("workFlag", statueInfo.get(position).getI_TYPE());

                startActivity(intent);
            }

            @Override
            public void OnClickListenerDone(int position) {//確認
                aboutAlert("確認結束？無法新增！",Constants.MESSAGE_DONE);
                iId=statueInfo.get(position).getI_ID();
            }
        });
    }

    /**
     * 刪除單頭
     * @param i_id 單頭
     * @param i_item 人員
     * @param flag 標誌
     */
    private void deleteHead(String i_id, String i_item, String flag) {

        final String url = Constants.HTTP_DELETE_BY_FLAG+"?i_id="+i_id+
                "&i_item="+i_item+"&flag="+flag; //此處寫上自己的URL

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    String result = HttpUtils.queryStringForPost(url);

                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {

                                Message message = new Message();
                                message.what = Constants.MESSAGE_DELETE_SUCCESS;
                                message.obj = jsonObject.get("errMessage").getAsString();
                                mHandler.sendMessage(message);
                            }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //基本信息下拉   傳值：flag type
    private void getType(String flag){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_BASIC_INFO + "?flag=" + flag;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        typeInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            typeInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_TYPE;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
        private void setType(){
            List<String> typeName=new ArrayList<>();
            for (int i = 0;i<typeInfo.size();i++){
                typeName.add(typeInfo.get(i).getNAME());
            }
            //稽核課隊下拉列表選擇
            spType.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, typeName));
            spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    type=typeName.get(position);
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }
//    基本信息下拉   傳值：flag i_status
    private void getStatus(String flag){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_BASIC_INFO + "?flag=" + flag;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        statueInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            statueInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_STATUS;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
        private void setStatus(){
            List<String> statueName=new ArrayList<>();
            for (int i = 0;i<statueInfo.size();i++){
                statueName.add(statueInfo.get(i).getNAME());
            }
            //稽核課隊下拉列表選擇
            spStatus.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, statueName));
            spStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    statue=statueName.get(position);
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }

    Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(KHMainListActivity.this, msg.obj.toString());
//                    finish();
                    break;
                case Constants.MESSAGE_SET_TEXT://text賦值
                    khHeadListAdapter = new KHHeadListAdapter(KHMainListActivity.this,statueInfo);
                    lvKHHead.setAdapter(khHeadListAdapter);
                    setListViewHeightBasedOnChildren(lvKHHead);
                    clickSeeOrAdd();
//                    aboutAlert(msg.obj.toString(),MESSAGE_SET_TEXT);
                    break;
                case Constants.MESSAGE_DONE://提交響應
                    check();
                    break;
                case Constants.MESSAGE_ALERT://提交響應
//                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
                    break;
                case MESSAGE_SET_TYPE:
                    setType();
                    getStatus("i_status");
                    break;
                case MESSAGE_SET_STATUS:
                    setStatus();
                    check();
                    break;
                    case Constants.MESSAGE_DELETE_SUCCESS:
                        check();
                        break;
            }
            super.handleMessage(msg);
        }
    };

    //提交前檢查
    private void check(){
        if(FoxContext.getInstance().getLoginId().equals("")){
            ToastUtils.showLong(KHMainListActivity.this,"登錄超時,請退出重新登錄!");
            return;
        }
        if (TimeDateUtils.daysDeviationDate(tvDateStart.getText().toString(),tvDateEnd.getText().toString())<=0){
            ToastUtils.showShort(KHMainListActivity.this,"請重新確認日期！");
            return;
        }
        if (tvDateStart.getText().toString().equals("")){
            ToastUtils.showShort(KHMainListActivity.this,"請確認開始日期！");
            return;
        }
        if (tvDateEnd.getText().toString().equals("")){
            ToastUtils.showShort(KHMainListActivity.this,"請確認結束日期！");
            return;
        }
        upMsessage();
    }
    //提交信息
    private void upMsessage() {

        final String url = Constants.HTTP_VIEW_LIST+"?i_empno="+FoxContext.getInstance().getLoginId()+"&i_date_s="+tvDateStart.getText().toString()+
                "&i_date_e="+tvDateEnd.getText().toString()+"&i_type="+type+"&i_status="+statue; //此處寫上自己的URL

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    String result = HttpUtils.queryStringForPost(url);

                    Gson gson = new Gson();
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {

                            JsonArray array = jsonObject.get("data").getAsJsonArray();
                            if (!array.equals(null)){
                                statueInfo = new ArrayList<KHInfo>();

                                for (JsonElement type : array) {
                                    KHInfo humi = gson.fromJson(type, KHInfo.class);
                                    statueInfo.add(humi);
                                }
                                Message message = new Message();
                                message.what = Constants.MESSAGE_SET_TEXT;
                                message.obj = "此条件无数据！";
                                mHandler.sendMessage(message);

                        } else {
                                Message message = new Message();
                                message.what = Constants.MESSAGE_TOAST;
                                message.obj = jsonObject.get("errMessage").getAsString();
                                mHandler.sendMessage(message);
                            }}
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /*時間選擇*/
    private int year, month, day;
    private void initDateTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) ;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }
    private StringBuffer date, time;
    private void show(String from){
        AlertDialog.Builder builder = new AlertDialog.Builder(KHMainListActivity.this);
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (date.length() > 0) { //清除上次记录的日期
                    date.delete(0, date.length());
                }
                if (from.equals("start")) {
                    tvDateStart.setText(date.append(String.valueOf(year)).append("-").append(String.valueOf(month + 1)).append("-").append(day));
                }else{
                    tvDateEnd.setText(date.append(String.valueOf(year)).append("-").append(String.valueOf(month + 1)).append("-").append(day));
                }
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(KHMainListActivity.this, R.layout.dialog_date, null);
        final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker);
        dialog.setTitle("设置日期");
        dialog.setView(dialogView);
        dialog.show();
        //初始化日期监听事件
        datePicker.init(year, month , day, this);
    }
    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        this.year = year;
        this.month = monthOfYear;
        this.day = dayOfMonth;
    }
    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("確認信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==Constants.MESSAGE_TOAST){
                            deleteHead(iId,"","head");
                        }else if(type==Constants.MESSAGE_DONE){

                            confirmById(iId);
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
//                        if (type==MESSAGE_TOAST){
//                            finish();
//                        }else if(type==MESSAGE_UP){
//                            check();
//                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    /**
     * 結束訪談
     * @param iId
     */
    private void confirmById(String iId) {
        final String url = Constants.HTTP_CONFIRM_BY_ID+"?i_id="+iId; //此處寫上自己的URL

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    String result = HttpUtils.queryStringForPost(url);

                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {

                            Message message = new Message();
                            message.what = Constants.MESSAGE_DONE;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
